import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import {gmprotips as protip} from '../utils/tips.js'
import {message} from 'ant-design-vue'
import NProgress from 'nprogress'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if(localStorage.getItem('token')){
      config.headers['token']=localStorage.getItem('token');
    }
    
    NProgress.start();
    if(config.method=='post'&&!config.iscommon&&(config.url!='/web/v1/member/article/add2'&&config.url!='/web/v1/member/article/edit2'&&config.url!='/web/v1/member/sort/video/add'&&config.url!='/web/v1/member/sort/video/update')){
      if(config.isMustCust!=false)
      {
        config.headers['Content-Type']='application/x-www-form-urlencoded; charset=UTF-8'
        config.transformRequest=function (data) {
          let ret = ''
          for (let it in data) {
            ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
          }
          return ret
        }
      }
    }
    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    if(response.data.status){
      response.data.code=0;
    }
    const res = response.data;
    if(res.data&&(res.data.images||res.data.image||res.data.article||res.data.games||res.data.articles||res.data.works||res.data.collections||res.data.searchs)){
      res.code=0;
    }
    NProgress.done();
    
    if (res.code !== 0&&!res.access_token) {
      message.warn(res.msg||'Error')
      return res
    } else {
      if(response.config.callbackFn){
        response.config.callbackFn(res);
      }else{
        return res;
      }
    }
  },
  error => {
    NProgress.done();
    if(error&&error.response&&error.response.status==401){
      localStorage.removeItem('userInfo')
      localStorage.removeItem('userId')
      localStorage.removeItem('token')
      message.error(error.response.data.msg);
      setTimeout(()=>{
        location.href='/'
      },1500)
    }else{
      message.error('网络请求超时,请重试!');
    }
    return Promise.reject(error)
  }
)

export default service
